﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Collections;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Diagnostics;
using DoubleH.Utility.Configuration;

namespace DoubleH.Utility.UC
{
    /// <summary>
    /// Interaction logic for TextBox.xaml
    /// </summary>    
    public partial class TextBoxExt : Canvas
    {
        class FormatDisplay
        {
            string[] displayColumn = null;
            public FormatDisplay(string[] displayColumn)
            {
                this.displayColumn = displayColumn;
            }

            public DataRow Row { get; set; }

            public string FirstText
            {
                get
                {
                    if ( Row == null)
                        return base.ToString();
                    else
                            return Row[0] as string;
                }
            }

            public string DisplayText
            {
                get
                {
                    if (displayColumn == null || Row == null)
                        return base.ToString();
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in displayColumn)
                            sb.Append(Row[str] as string + " ");

                        return sb.ToString();
                    }
                }
            }
        }

        public delegate void Selected(DataRow row);
        public event Selected SelectedRow;

        private VisualCollection controls;
        private TextBox textBox;
        private ComboBox comboBox;
        //private ObservableCollection<DataRow> autoCompletionList;
        private ObservableCollection<DataRow> filterRows = new ObservableCollection<DataRow>();
        private System.Timers.Timer keypressTimer;
        private delegate void TextChangedCallback();
        private bool insertText;
        private int delayTime;
        private int searchThreshold;
        string sqlString = string.Empty;
        string[] searchColumn = null;
        string[] displayColumn = null;
        string sql = string.Empty;
        ObservableCollection<FormatDisplay> allRow = new ObservableCollection<FormatDisplay>();

        public TextBoxExt()
        {
            controls = new VisualCollection(this);
            InitializeComponent();

            InitUI();
            InitVar();
        }

        private void InitUI()
        {
            comboBox = new ComboBox();
            comboBox.IsSynchronizedWithCurrentItem = true;
            comboBox.IsTabStop = false;
            comboBox.SelectionChanged += new SelectionChangedEventHandler(comboBox_SelectionChanged);
            comboBox.MinWidth = 10;

            textBox = new TextBox();
            textBox.MinWidth = 10;
            textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
            textBox.VerticalContentAlignment = VerticalAlignment.Center;

            controls.Add(comboBox);
            controls.Add(textBox);
        }

        private void InitVar()
        {
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
                return;

            keypressTimer = new System.Timers.Timer();
            keypressTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);

            searchThreshold = DoubleHConfig.AppConfig.SearchThreshold;        // default threshold to 2 char
            delayTime = DoubleHConfig.AppConfig.DelayTime;
        }

        public string Text
        {
            get { return textBox.Text; }
            set
            {
                insertText = true;
                textBox.Text = value;
            }
        }

        bool showList = true;
        public bool ShowList
        {
            get { return showList; }
            set { showList = value; }
        }

        public void Init(string tableName, string[] searchColumn, string[] displayColumn, string selectColumn)
        {
            Debug.Assert(!string.IsNullOrEmpty(tableName));
            Debug.Assert(displayColumn != null);
            Debug.Assert(searchColumn!= null);

            this.searchColumn = searchColumn;
            this.displayColumn = displayColumn;
            comboBox.DisplayMemberPath = "DisplayText";
           
            StringBuilder sb = new StringBuilder("select ");
            foreach (string str in displayColumn)
                sb.Append(str + ",");

            sb.Remove(sb.Length - 1, 1);
            sb.Append(" from " + tableName + " where ");
            sqlString = sb.ToString();
        }

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null != comboBox.SelectedItem)
            {
                insertText = true;
                FormatDisplay fd = comboBox.SelectedItem as FormatDisplay;
                textBox.Text = fd.FirstText;
                //DataRow row = (DataRow)comboBox.SelectedItem;
                //textBox.Text = row[displayColumn[0]].ToString();

                if (SelectedRow != null)
                    SelectedRow(fd.Row);
            }
        }

        private void TextChanged()
        {
            if (!showList)
                return;

            try
            {
                filterRows.Clear();
                if (textBox.Text.Length >= searchThreshold)
                {
                    string str2="(";
                    foreach (string str in searchColumn)
                        str2 += (str + " like '%"+Text+"%' or ");

                    str2=str2.Remove(str2.Length-3);
                    str2 += ")";
                    allRow.Clear();
                    foreach (DataRow entry in FCNS.Data.SQLdata.GetDataRows(sqlString + str2))
                        allRow.Add(new FormatDisplay(displayColumn) { Row = entry });

                    comboBox.ItemsSource = allRow;
                    //comboBox.ItemsSource = filterRows.Distinct<DataRow>(new NormalUtility.Compare<DataRow>((x,y)=>x[0].ToString().Trim()==y[0].ToString().Trim()));
                    //comboBox.Items.Clear();
                    //foreach (DataRow r in filterRows.Distinct<DataRow>(new NormalUtility.Compare<DataRow>((x, y) => x[0].ToString().Trim() == y[0].ToString().Trim())))
                    //    comboBox.Items.Add(r);

                    comboBox.IsDropDownOpen = comboBox.HasItems;
                    //comboBox.SelectedItem = null;
                }
                else
                    comboBox.IsDropDownOpen = false;
            }
            catch { }
        }

        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            keypressTimer.Stop();
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new TextChangedCallback(this.TextChanged));
        }

        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (insertText) 
                insertText = false;
            else
            {
                if (delayTime > 0)
                {
                    keypressTimer.Interval = delayTime;
                    keypressTimer.Start();
                }
                else TextChanged();
            }
        }

        protected override Size ArrangeOverride(Size arrangeSize)
        {
            textBox.Arrange(new Rect(arrangeSize));
            comboBox.Arrange(new Rect(arrangeSize));
            return base.ArrangeOverride(arrangeSize);
        }

        protected override Visual GetVisualChild(int index)
        {
            return controls[index];
        }

        protected override int VisualChildrenCount
        {
            get { return controls.Count; }
        }
    }
}